package org.book.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.book.dao.BorrowBean;
import org.book.service.BorrowService;

/**
 * Servlet implementation class BorrowServlet
 */
@WebServlet("/BorrowServlet")
public class BorrowServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BorrowServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		
		
		
		String textName = request.getParameter("textName");
		Object obj = request.getParameter("pageCurrent");
		//修改删除之后保持页码
		Object obj2 = request.getAttribute("pageCurrent2");
		BorrowService borrowService = new BorrowService();
		
		//借阅 写在List列表之前
		String book = request.getParameter("book_id");
		String user = request.getParameter("user_id");
		if(book!=null&&user!=null) {
			String rentTime = request.getParameter("rentTime");
			String returnTime = request.getParameter("returnTime");
			borrowService.add(new BorrowBean(rentTime,returnTime), Integer.parseInt(book), Integer.parseInt(user));
			
		}
		
		List<BorrowBean> list = new ArrayList<>();
		
		int pageCurrent = 1;
		
		if(obj!=null) {
			pageCurrent = Integer.parseInt(obj.toString());
		}
		//页码保持
		if(obj2!=null) {
			pageCurrent = Integer.parseInt(obj2.toString());
		}
		//搜索
		if(textName!=null) {
			list = borrowService.getLike(textName);
		}
		//显示
		else {
			list = borrowService.getList(pageCurrent,10);
		}
		
		request.setAttribute("list", list);
		
		request.setAttribute("pageCurrent", pageCurrent);
		
		request.setAttribute("count", borrowService.getCount());
		
		request.getRequestDispatcher("pages/home/borrow.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
